﻿using System;
using System.Web;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Shop
{
    public partial class OrderProduct : System.Web.UI.Page
    {
        private Product _selectedProduct;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Check if product is set!
            if (Session["selectedProduct"] != null)
            {
                MultiViewOrder.SetActiveView(validData);
                _selectedProduct = (Product)Session["selectedProduct"];

                //Set datalabels
                setLabels();

                //Set error label not visible
                noCredit.Visible = false;
            }
            else
            {
                MultiViewOrder.SetActiveView(invalidData);
            }
        }

        protected void setLabels()
        {
            if (_selectedProduct != null)
            {
                ProductID.Text = _selectedProduct.Id.ToString();
                ProductName.Text = _selectedProduct.Name;
                ProductPrice.Text = _selectedProduct.Price + " Miles";
            }
        }

        protected void OrderButton_Click(object sender, EventArgs e)
        {
            //Check if user is logged in
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/Account/Login.aspx?ReturnUrl=%2fShop%2fOrderProduct.aspx");
            }

            //Get user
            UserService svc = new UserService();
            User user = svc.GetUserByName(HttpContext.Current.User.Identity.Name);

            //Check if user has enough credits
            if (user.Points < _selectedProduct.Price)
            {
                //Show credit shortage
                noCredit.Visible = true;
            }
            else
            {
                //Generate url
                string url = RngUtils.GetUrlString();

                //Send email to user
                Mailer mailer = new Mailer();
                mailer.SendOrderConfirmMail(user, _selectedProduct, url);

                //Set confirmed view
                MultiViewOrder.SetActiveView(orderConfirmed);

                //Add order to database
                OrderService orderService = new OrderService();
                Order orderToInsert = new Order
                {
                    ProductID = _selectedProduct.Id,
                    UserID = user.Id,
                    OrderURL = url,
                    DateOrdered = DateTime.Now,
                    confirmed = false
                };
                orderService.InsertOrder(orderToInsert);
            }
        }
    }
}